const app = getApp();
const qiniuUploader = require("../../utils/qiniuUploader.js");
const AV = require("../../utils/av-weapp-min.js");
const Config = require('../../config.js');

Page({
  data: {
    currentTab: 0,
    slider_value: 0,
    showAddPicture: true,
    pictures: [],
    startTimeValue: '09:00',
    endTimeValue: '18:00',
    content: "",
    focus: true,
    uptoken : '',
    isSearchVisible: true,
    texttareafocus: true,
    inputfocus: false,
    items: [
      { name: '房东', checked: 'true' },
      { name: '租客' },
      { name: '经纪人'},
    ],
    serverFeedObj : {
      imgs      : [], //店铺的图片地址
      ownerId   : '', //发布者Id
      desc      : '', //描述
      rentType: '', //押一付二
      rentDic: '', //朝北
      title     : '', //
      timePrice: [], //[{"time":"05:30-08:00", "price":"3000"}, {"time":"20:00-05:00", "price":"6000"}]
      rentRequire: [], //["一年起租","租户稳定"]
      area      : '', //xx平米
      location: '', //经纬度:23.1308,113.401962
      img       : '', //房子展示图
    }
  },

  swichNav: function(e) {
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      this.setData({
        currentTab: e.target.dataset.current
      })
    }
  },

  bindChange: function(e) {
    this.setData({
      currentTab: e.detail.current
    });
    if (this.data.currentTab == 0) {
      this.setData({
        isSearchVisible: true,
      })
    } else {
      this.setData({
        isSearchVisible: false,
      })
    }
  },

  //添加图片
  addpicture(event) {
    const that = this;
    let count = 6 - that.data.pictures.length;
    wx.chooseImage({
      count: count, // 最多可以选择的图片张数，默认6
      sizeType: ['compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function(res) {
        console.log("addpicture----->", res.tempFilePaths[0]);
        let temps = that.data.pictures.concat(res.tempFilePaths);
        let showAddPicture = true;
        if (temps.length >= 6) {
          showAddPicture = false;
        };
        that.setData({
          pictures: temps,
          showAddPicture: showAddPicture,
        })
      },

    })
  },
  //显示图片
  showpictures(event) {
    const that = this;
    that.setData({
      showPictures: !that.data.showPictures
    })
  },
  //删除图片
  deletePicture(event) {
    const that = this;
    const id = event.currentTarget.dataset.id;
    let temps = that.data.pictures;
    temps.splice(id, 1);
    let showAddPicture = true;
    if (temps.length >= 4) {
      showAddPicture = false;
    };
    that.setData({
      pictures: temps,
      showAddPicture: showAddPicture
    })
  },

  timePickerBindchangeStart: function(e) {
    this.setData({
      startTimeValue: e.detail.value
    })
  },

  timePickerBindchangeEnd: function(e) {
    this.setData({
      endTimeValue: e.detail.value
    })
  },

  doChoiceArea: function(e) {
    console.log(e);
    wx.navigateTo({
      url: '../switchcity/switchcity',
    })
  },

  radioChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
  },
  getQiniuUploadToken : function() {
    
    let token = this.data.uptoken;
    if (token && token.length > 0) {
      this.doUpload(token);
      return;
    }
    wx.showLoading();
      AV.Cloud.run('uploadToken').then((data)=>{
        wx.hideLoading();
        console.log('getQiniuUploadToken----->data:', data.token);
        if (data.token) {
          this.data.uptoken = data.token;
          this.doUploadCal(data.token);
        }
      },function(err){
        wx.hideLoading();
        console.log('getQiniuUploadToken----->err:', err);
      });
  },

  onJoin : function(e) {
    this.getQiniuUploadToken();

  },

  doUploadCal : function(token) {
    let pics = this.data.pictures;
    if (!pics || pics.length <= 0) {
      wx.showToast({
        title: '请先选择图片',
      })
      return;
    }
    console.log("onJoin------>length: ", pics.length);
    let count = 0;
    for (let i = 0; i < pics.length; i++) {
      wx.showLoading({
        title: '上传中...',
      });
      count++;
      console.log("onJoin------>", pics[i]);
      this.doUpload(token, pics[i]).then((data) => {
        wx.hideLoading();
        console.log("promise------>data:", data);
        this.data.serverFeedObj.imgs.push(data.uploadUrl);
        if (count == pics.length) {
          this.doSaveToServer();
        }
      }).catch((error)=>{
        wx.hideLoading();
        console.log("promise------>error:", error);
        if (count == pics.length) {
          this.doSaveToServer();
        }
      });
    }
  },

  doUpload : function(token, fileName) {

    return new Promise((resolve, reject)=>{
      console.log("onJoin------>src:", fileName);
      qiniuUploader.upload(fileName, (res) => {
        console.log("onJoin------>suc:", res);

        // let domain = Config.QINIU_BASE_URL;
        let url = Config.configure.QINIU_BASE_URL + res.imageURL;
        console.log("onJoin------>suc_url:"+url);
        return resolve({ uploadUrl: url, key : res.key, fsize : res.fsize, });
    }, (error) => {
      console.log("onJoin------>err:", error);
      return reject(error);
    }, {
        region: 'SCN',//华南
        domain: '',
        key: '',
        uptoken: token,
        uploadURL: 'https://up-z2.qbox.me'
      }, (res) => {
        console.log('上传进度', res.progress)
        console.log('已经上传的数据长度', res.totalBytesSent)
        console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
      });
    });

    
  },

  doSaveToServer : function() {

    let userId = AV.User._currentUser.id;
    let tp = '[{ "time": "05:30-08:00", "price": "3000" }, { "time": "20:00-05:00", "price": "6000" }]';
    let rr = ["一年起租", "租户稳定"];
    let location = new AV.GeoPoint(23.1308,113.401962);
    let RentRoom = AV.Object.extend('RentRoom');
    let rentRoom = new RentRoom();
    rentRoom.set('title', '员村');
    rentRoom.set('ownerId', userId);
    rentRoom.set('description', "这个房子很不错啊");
    rentRoom.set('images', this.data.serverFeedObj.imgs);
    rentRoom.set('img', this.data.serverFeedObj.imgs[0]);
    rentRoom.set('rentType', "押一付三");
    rentRoom.set('rentDirection', "朝南");
    rentRoom.set('timePrice', tp);
    rentRoom.set('rentRequire', rr);
    rentRoom.set('location', location);
    rentRoom.set('owner', "房东");

    wx.showLoading({
      title: '保存数据中...',
    });
    rentRoom.save().then((res)=>{
      console.log("doSaveToServer-====>suc:", res);
      wx.hideLoading();
      wx.showToast({
        title: '请求成功',
        success : function(){
          wx.navigateBack({});
        }
      })

    }, (error)=>{
      console.log("doSaveToServer-====>error:", error);
      wx.hideLoading();
    });
  },
  listenerInfoInput:  function (e) {
    this.setData({
      texttareafocus: true,
      inputfocus: false
    });
  },

  listenerPhoneInput: function (e) {
    this.setData({
      texttareafocus: false,
      inputfocus: true
    });
  },

})